<template>
  <base-container>
    <!-- 搜索栏 -->
    <avue-table-search
      :option="searchOption"
      v-model="searchParams"
      @search-change="loadTableSearch"
      @search-reset="loadTableSearchReset"
    />
    <!-- 卡片容器 -->
    <base-table-card>
      <template #header-right>
        <el-button type="primary" v-auth="[PERMS.ROLE.ADD]" @click="handleGoToAddRole">新增角色</el-button>
      </template>
      <avue-crud
        ref="avueCrudRef"
        :option="tableOption"
        :data="tableData"
        v-model="formData"
        :page="page"
        :table-loading="tableLoading"
        :before-open="handleBeforeOpen"
        @refresh-change="loadGetTableData"
        @current-change="loadTablePageChange"
        @size-change="loadTablePageSizeChange"
        @row-save="loadAdd"
        @row-update="loadEdit"
      >
        <template #menu="{ row }">
          <template v-if="row.roleType != 1">
            <el-button type="primary" text v-auth="[PERMS.ROLE.VIEW]" @click="handleShowRoleDetail(row.id)">
              查看
            </el-button>
            <el-button type="primary" text v-auth="[PERMS.ROLE.UPDATE]" @click="handleGotoUpdateRole(row.id)">
              编辑
            </el-button>
            <el-button type="info" text v-auth="[PERMS.ROLE.DELETE]" :disabled="row.users > 0" @click="loadDel(row)">
              删除
            </el-button>
          </template>
        </template>
      </avue-crud>
    </base-table-card>

    <role-detail
      v-model="showRoleDetail"
      :size="900"
      lock-scroll
      :role-id="currentRoleId"
      destroy-on-close
      @close="handleCloseRoleDetail"
    />
  </base-container>
</template>

<script setup>
  import RoleDetail from "@/views/setting/permission/components/RoleDetail.vue";

  import Option from "@/crudOption/setting/permission/role";

  // 获取路由实例
  const router = useRouter();

  onMounted(() => {
    // 获取表格数据
    loadGetTableData();
  });

  // avue-crud 组件实例
  const avueCrudRef = ref({});

  // 增删改查 hook
  let {
    data: tableData,
    loading: tableLoading,
    page: page,
    search: searchParams,
    form: formData,
    get: loadGetTableData,
    add: loadAdd,
    edit: loadEdit,
    del: loadDel,
    pageNumChange: loadTablePageChange,
    pageSizeChange: loadTablePageSizeChange,
    searchReset: loadTableSearchReset,
    searchChange: loadTableSearch,
  } = useCrudHook({
    get: Api.role.GetRolePage,
    add: Api.role.AddRole,
    edit: Api.role.UpdateRole,
    del: Api.role.DeleteRole,
    delConfirm: {
      title: "提示",
      content: "确认删除该角色吗？",
      type: "warning",
    },
    getParamsFormat: params => {
      // 新增时间
      if (params.createTime && params.createTime.length === 2) {
        params.createTimeStart = params.createTime[0];
        params.createTimeEnd = params.createTime[1];
      }
      // 编辑时间
      if (params.updateTime && params.updateTime.length === 2) {
        params.updateTimeStart = params.updateTime[0];
        params.updateTimeEnd = params.updateTime[1];
      }
      // 删除多余参数
      delete params.updateTime;
      delete params.createTime;
      // 返回查询参数
      return params;
    },
  });

  // 获取 搜索配置 和 表格配置
  const { searchOption, tableOption } = Option(formData);

  // 弹窗打开前
  const handleBeforeOpen = done => {
    // 获取菜单树
    loadGetMenuTree();
    nextTick(done);
  };

  // 菜单树数据
  const menuTreeData = ref([]);
  // 菜单树加载状态
  const menuTreeLoading = ref(false);

  // 获取菜单树数据
  const loadGetMenuTree = async () => {
    // 开始加载
    menuTreeLoading.value = true;
    // 运管菜单树
    Api.menu
      .GetMenuTree({ platform: 2 })
      .then(res => {
        menuTreeData.value = res.data || [];
      })
      .finally(() => {
        // 结束加载
        menuTreeLoading.value = false;
      });
  };

  // 记录当前查看详情的角色ID
  const currentRoleId = ref(null);

  // 是否显示角色详情
  const showRoleDetail = ref(false);

  // 显示角色详情
  const handleShowRoleDetail = roleId => {
    showRoleDetail.value = true;
    currentRoleId.value = roleId;
  };

  // 监听角色详情关闭
  const handleCloseRoleDetail = () => {
    showRoleDetail.value = false;
    currentRoleId.value = null;
  };

  // 跳转新增页面
  const handleGoToAddRole = () => {
    router.push({ path: ROUTE_PATHS.ROLE.ADD });
  };

  // 跳转到编辑页面
  const handleGotoUpdateRole = roleId => {
    router.push({ path: ROUTE_PATHS.ROLE.UPDATE, query: { roleId } });
  };

  // 监听权限变化，更新操作栏是否显示
  tableOption.value.menu = computed(() => hasAuth([PERMS.ROLE.VIEW, PERMS.ROLE.UPDATE, PERMS.ROLE.DELETE]));

  // 监听菜单操作权限变化，更新操作菜单宽度
  tableOption.value.menuWidth = computed(() => {
    let width = 0;
    if (hasAuth(PERMS.ROLE.VIEW)) width += 60; // 2个字按钮宽度 60px
    if (hasAuth(PERMS.ROLE.UPDATE)) width += 60; // 2个字按钮宽度 60px
    if (hasAuth(PERMS.ROLE.DELETE)) width += 60; // 2个字按钮宽度 60px
    return width;
  });
</script>
<style lang="scss" scoped></style>
